package com.yuerlive.rainbow.module.game;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mrd.game.message.HOpCodeEx;
import com.mrd.game.message.RainbowMessage;
import com.mrd.mina.MinaCallback;
import com.mrd.mina.MinaHelper;
import com.mrd.packet.Packet;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.common.AppConfig;
import com.yuerlive.rainbow.common.BaseRecycleViewAdapter;
import com.yuerlive.rainbow.entity.BankerFlowData;
import com.yuerlive.rainbow.entity.BaseData;
import com.yuerlive.rainbow.entity.GameInfo;
import com.yuerlive.rainbow.entity.LiveDetailData;
import com.yuerlive.rainbow.entity.NiuniuHistory;
import com.yuerlive.rainbow.entity.Poker;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.entity.UserInfo;
import com.yuerlive.rainbow.module.game.adapter.BankerFlowAdapter;
import com.yuerlive.rainbow.module.game.adapter.BankerListAdapter;
import com.yuerlive.rainbow.module.game.adapter.CatMouseHistoryAdapter;
import com.yuerlive.rainbow.module.game.adapter.NiuNiuHistoryAdapter;
import com.yuerlive.rainbow.module.game.presenter.GameSanguoContract;
import com.yuerlive.rainbow.module.game.presenter.GameSanguoPresenter;
import com.yuerlive.rainbow.module.live.LiveRoomActivity;
import com.yuerlive.rainbow.module.live.fragment.FragmentLayer;
import com.yuerlive.rainbow.module.playlive.PlayLiveRoomActivity;
import com.yuerlive.rainbow.module.recharge.RechargeActivity;
import com.yuerlive.rainbow.observer.Observerable;
import com.yuerlive.rainbow.observer.ObserverableType;
import com.yuerlive.rainbow.utils.DeviceUtils;
import com.yuerlive.rainbow.utils.FormatUtil;
import com.yuerlive.rainbow.utils.GlideUtil;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.CircleImageView;
import com.yuerlive.rainbow.widget.CustomDialog;
import com.yuerlive.rainbow.widget.game.PokerGroup;
import com.yuerlive.rainbow.widget.game.PokerView;
import com.yuerlive.rainbow.widget.game.SanguoLayout;

import org.apache.mina.core.session.IoSession;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

import butterknife.BindBitmap;
import butterknife.BindColor;
import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by xiaoyi on 2017/7/14.
 * 三英战吕布
 */

public class FragmentGameSanguo extends FragmentGameBase implements SanguoLayout.OnDealListener,
        MinaCallback, UserProxy.OnUserChangeListener, GameSanguoContract.View {

    @BindView(R.id.sgLeft)
    SanguoLayout sgLeft;
    @BindView(R.id.sgCenter)
    SanguoLayout sgCenter;
    @BindView(R.id.sgRight)
    SanguoLayout sgRight;

    @BindView(R.id.llSettle)
    LinearLayout llSettle;
    @BindView(R.id.tvSettleMine)
    TextView tvSettleMine;
    @BindView(R.id.tvSettleBanker)
    TextView tvSettleBanker;

    @BindView(R.id.pgBanker)
    PokerGroup pgBanker;

    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.tv_recharge)
    TextView tvRecharge;
    @BindView(R.id.tvchips10)
    TextView tvchips10;
    @BindView(R.id.llchips10)
    LinearLayout llchips10;
    @BindView(R.id.tvchips100)
    TextView tvchips100;
    @BindView(R.id.llchips100)
    LinearLayout llchips100;
    @BindView(R.id.tvchips1000)
    TextView tvchips1000;
    @BindView(R.id.llchips1000)
    LinearLayout llchips1000;
    @BindView(R.id.llchips10000)
    LinearLayout llchips10000;
    @BindView(R.id.tvchips10000)
    TextView tvchips10000;
    @BindView(R.id.ivHistory)
    ImageView ivHistory;
    @BindView(R.id.llBottom)
    LinearLayout llBottom;
    @BindView(R.id.pokerStart0)
    ViewGroup pokerStart0;
    @BindView(R.id.pokerStart1)
    ViewGroup pokerStart1;
    @BindView(R.id.pokerStart2)
    ViewGroup pokerStart2;
    @BindView(R.id.pokerStart3)
    ViewGroup pokerStart3;
    @BindView(R.id.tvState)
    TextView tvState;
    @BindView(R.id.tvTimer)
    TextView tvTimer;
    @BindView(R.id.tvBeBanker)
    TextView tvBeBanker;

    @BindView(R.id.tvBankerName)
    TextView tvBankerName;
    @BindView(R.id.ivBankerHeader)
    CircleImageView ivBankerHeader;
    @BindView(R.id.tvBankerGold)
    TextView tvBankerGold;

    @BindColor(R.color.white_50)
    int colorUnEnable;
    @BindColor(R.color.white)
    int colorWhite;
    @BindBitmap(R.drawable.gold_icon)
    Bitmap gold;
    @BindBitmap(R.drawable.gold_icon_gray)
    Bitmap goldGray;

    @BindString(R.string.format_banker_flow_negative)
    String bankerFlowNegative;
    @BindString(R.string.format_banker_flow_positive)
    String bankerFlowPositive;

    @BindString(R.string.settle_mine)
    String settleMine;
    @BindString(R.string.settle_banker)
    String settleBanker;

    /*game-----------------------------*/
    private float serviceRate = 0.02f;

    private final static int GAME_ID = 3;
    private boolean canDeal;
    private long requestGameStateTime;
    private int liveID;
    private GameInfo gameInfo;
    private int chessboardId;
    private int dealCountDown = 30;
    private static final int VAULE_DEALCOUNTDOWN = 30;
    private RainbowMessage.GCResultRet niuniuResult;

    private int mBankerID = 1;

    int chipsSelected = 10;
    int myDealLeft = 0;
    int myDealCenter = 0;
    int myDealRight = 0;
    int myDealTotal = 0;

    int dealTotalLeft;
    int dealTotalCenter;
    int dealTotalRight;

    int myWinLeft;
    int myWinCenter;
    int myWinRight;

    private boolean inBankerList = false;

    int myAvailableTotal = 0;

    Thread minaThread;
    private float rateLeft = 2.8f;
    private float rateCenter = 6.0f;
    private float rateRight = 2.8f;

    final static int CODE_FAPAI = 0X1001;  //发牌
    final static int CODE_KAIPAI = 0X1002; //开牌
    final static int CODE_RELAX = 0X1003; //休息一会
    final static int CODE_CALCULATE = 0X1004; //结算

    final static int CODE_DEAL = 0X2001;  //下注
    final static int CODE_UPDATE_DEAL = 0X2002;  //更新下注情况
    final static int CODE_DEAL_RESULT = 0X2003;  //下注结果

    final static int CODE_DEAL_COUNTDOWN = 0X3001; //下注倒计时
    final static int CODE_CALCULATE_COUNTDOWN = 0X3002;//结算倒计时

    final static int CODE_CHANGE_GAME = 0X4001; //切换游戏
    final static int CODE_CLOSE_GAME = 0X4002; //关闭游戏

    final static int CODE_BANKER_LIST = 0X5001;  //上庄列表
    final static int CODE_UPDOWN_BANKER = 0X5002; //上下庄返回

    final static int CODE_SWEET_COUNT = 0X6001;  //彩虹豆数量

    private GameHandler mHandler;
    /*--------------------------------*/
    private User user;
    private LiveDetailData liveDetail;

    private ScaleAnimation stateShowAnim;

    private CustomDialog hisResult;  //历史输赢
    private CustomDialog bankerFlowDialog;  //获胜奖励
    private CustomDialog bankerListDialog;  //上庄列表

    private CustomDialog downBankerDialog; // 下庄提醒

    private BankerListAdapter bankerListAdapter;

    private ListView lvHistory;
    private NiuNiuHistoryAdapter hisAdapter;
    private List<NiuniuHistory> mHisDatas = new ArrayList<>();
    private TextView tvWins;

    private BankerFlowAdapter bankerFlowAdapter;
    private List<BankerFlowData.BankerFlowItem> bankerFlowDatas = new ArrayList<>();

    private List<RainbowMessage.User> bankerList = new ArrayList<>();

    @Override
    public boolean isDialogShowing() {
        boolean isShowing = hisResult != null && hisResult.isShowing();
        if (isShowing) return isShowing;
        isShowing = bankerFlowDialog != null && bankerFlowDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = bankerListDialog != null && bankerListDialog.isShowing();
        if (isShowing) return isShowing;
        isShowing = downBankerDialog != null && downBankerDialog.isShowing();
        return isShowing;
    }

    public FragmentGameSanguo() {
        presenter = new GameSanguoPresenter(this);
        user = UserProxy.getUser();
    }

    @Override
    public void setLiveDetail(LiveDetailData liveDetailData) {
        if (liveDetailData == null) return;
        this.liveDetail = liveDetailData;
        liveID = Integer.parseInt(liveDetail.getInfo().getLiveId());
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_game_sanguo;
    }

    @Override
    public void initViews(View root) {
        showBankerInfo(null);
        if (mActivity instanceof PlayLiveRoomActivity) {
            liveID = Integer.parseInt(user.getUserInfo().getLiveId());
            ((PlayLiveRoomActivity) mActivity).setGameID(GAME_ID);
        }
        ((GameSanguoContract.Presenter) presenter).getGameInfo("" + GAME_ID);
        mHandler = new GameHandler(this);
        minaThread = new Thread(() -> {
            MinaHelper.getInstance().connect(this, false);
        });
        minaThread.start();

        UserProxy.addListener(this);
        initHisResultDialog();
        initBankerFlowDialog();
        initDownBankerDialog();
        initBankerListDialog();
        setListener();
        stateShowAnim = (ScaleAnimation) AnimationUtils.loadAnimation(mActivity, R.anim.state_show);
    }


    @Override
    public void onDeal(View v) {
        if (canDeal) {
            if (mBankerID == (Integer.parseInt(user.getUserId()))) {
                showSnackbar(getRootView(mActivity), "庄家不允许押注");
            } else {
                if (checkSweet()) {
                    sendDealMsg(v.getId() == R.id.sgLeft ? 1 : v.getId() == R.id.sgCenter ? 2 : 3);

                } else {
                    if (myDealCenter + myDealCenter + myDealRight > 0)
                        showSnackbar(getRootView(mActivity), "当前余额不足(已下注)");
                    else
                        showSnackbar(getRootView(mActivity), "彩虹糖不足");
                }
            }
        }
    }

    private void setListener() {
        sgLeft.setOnDealListener(this);
        sgCenter.setOnDealListener(this);
        sgRight.setOnDealListener(this);

    }


    @OnClick({
            R.id.llchips10, R.id.llchips100, R.id.llchips1000, R.id.llchips10000, R.id.ivHistory, R.id.tv_recharge,
            R.id.tvBeBanker, R.id.tvBankerHis, R.id.ivBankerHeader, R.id.tvBankerName

    })
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llchips10:
                changeChips(10);
//                sendInLiveRequest();
                break;
            case R.id.llchips100:
                changeChips(100);
                break;
            case R.id.llchips1000:
                changeChips(1000);
                break;
            case R.id.llchips10000:
                changeChips(10000);
                break;
            case R.id.ivHistory:
                ((GameSanguoContract.Presenter) presenter).getGameHistory("" + liveID, "" + GAME_ID);
                break;
            case R.id.tv_recharge:
                jumpToActivity(RechargeActivity.class);
                break;
            case R.id.tvBeBanker:
                if (mBankerID == Integer.parseInt(user.getUserId())) {
                    downBankerDialog.show();
                } else {
                    if (user.getUserInfo().getRainbowSweet() < 30000 || user.getUserInfo().getRainbowSweet()
                            - user.getUserInfo().getFreezeSweet() < 30000) {
                        showSnackbar(getRootView(mActivity), "彩虹糖不足30000，无法上庄");
                    } else {
                        getBankerList();
                    }
                }
                break;
            case R.id.tvBankerHis:
                ((GameSanguoContract.Presenter) presenter).getBankerFlow(liveID, mBankerID);
                break;
            case R.id.tvBankerName:
            case R.id.ivBankerHeader:
                if (mBankerID > 1) {
                    Observerable.getInstance().notifyChange(ObserverableType.GETBANKERINFO, String.valueOf(mBankerID));
                }
                break;

        }
    }

    private void changeChips(int value) {
        chipsSelected = value;
        switch (value) {
            case 10:
                tvchips10.setBackgroundResource(R.drawable.bg_niuniu_chips_selected);
                tvchips100.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips1000.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips10000.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                break;
            case 100:
                tvchips100.setBackgroundResource(R.drawable.bg_niuniu_chips_selected);
                tvchips10.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips1000.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips10000.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                break;
            case 1000:
                tvchips1000.setBackgroundResource(R.drawable.bg_niuniu_chips_selected);
                tvchips100.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips10.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips10000.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                break;
            case 10000:
                tvchips10000.setBackgroundResource(R.drawable.bg_niuniu_chips_selected);
                tvchips100.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips10.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                tvchips1000.setBackgroundResource(R.drawable.bg_niuniu_chips_unselected);
                break;
        }
    }

    private boolean checkSweet() {
        return myAvailableTotal >= (myDealTotal + chipsSelected) * 6;
    }

    /*下注*/
    private void sendDealMsg(int index) {
        RainbowMessage.CGBet.Builder builder = RainbowMessage.CGBet.newBuilder();
        builder.setGameId(GAME_ID);
        builder.setUserId(Integer.parseInt(user.getUserId()));
        builder.setLiveId(liveID);
        builder.setToken(UserProxy.getUser().getToken());
        builder.setIndex(index);
        builder.setChessboardId(chessboardId);
        builder.setValue(chipsSelected);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGBet, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        L.e(TAG, "time send before " + System.currentTimeMillis());
        MinaHelper.getInstance().sendMessageToServer(packet);
        L.e(TAG, "time  send after " + System.currentTimeMillis());

    }

    private void sendInLiveRequest() {
        User user = UserProxy.getUser();
        if (user == null) return;
        RainbowMessage.CGUserState.Builder builder = RainbowMessage.CGUserState.newBuilder();
//        builder.setToken(user.getToken());
        builder.setUserId(Integer.parseInt(user.getUserId()));
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGUserState, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }


    /*执行发牌动画*/
    private void doFapai() {
        try {
            canDeal = false;
            if (tvState == null) return;
            tvState.setVisibility(View.GONE);
            tvTimer.setVisibility(View.GONE);
            llSettle.setVisibility(View.GONE);
            AnimatorSet set = new AnimatorSet();
            Animator bankerAnim = playFapaiAnim(pgBanker, pokerStart0);
            Animator leftAnim = playFapaiAnim(sgLeft.getPokerGroup(), pokerStart1);
            Animator centerAnim = playFapaiAnim(sgCenter.getPokerGroup(), pokerStart2);
            Animator rightAnim = playFapaiAnim(sgRight.getPokerGroup(), pokerStart3);
            if (leftAnim != null) {
                leftAnim.setStartDelay(600);
            }
            if (centerAnim != null) {
                centerAnim.setStartDelay(1200);
            }
            if (rightAnim != null) {
                rightAnim.setStartDelay(1800);
            }
            set.playTogether(bankerAnim, leftAnim, centerAnim, rightAnim);
            set.start();
            set.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    if (tvState != null) {
                        tvState.postDelayed(() -> {
                            showState("开始下注");
                            if (GAMESTATE != 2 && tvState != null)
                                tvState.postDelayed(() -> tvState.setVisibility(View.GONE), 1000);
                        }, 1000);
                    }
                }
            });
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /*状态提示view*/
    private TextView showState(String text) {
        if (tvState == null) return null;
        tvState.setText(text);
        if (tvState.getVisibility() != View.VISIBLE) {
            tvState.startAnimation(stateShowAnim);
        }
        tvState.setVisibility(View.VISIBLE);
        return tvState;
    }

    /*发牌动画*/
    private Animator playFapaiAnim(PokerGroup parent, ViewGroup pokerStart) {
        try {
            AnimatorSet animatorSet = new AnimatorSet();
            List<Animator> animators = new ArrayList<>();
            int[] location = new int[2];
            pokerStart.getChildAt(0).getLocationOnScreen(location);
            for (int i = 0; i < pokerStart.getChildCount(); i++) {
                PropertyValuesHolder tx = PropertyValuesHolder.ofFloat("translationX", 0,
                        parent.pokerLocations.get(i)[0] - location[0]);
                PropertyValuesHolder ty = PropertyValuesHolder.ofFloat("translationY", 0,
                        parent.pokerLocations.get(i)[1] - location[1]);
                PropertyValuesHolder rotation = PropertyValuesHolder.ofFloat("rotation", 0,
                        720);
                ObjectAnimator animator = ObjectAnimator.ofPropertyValuesHolder(pokerStart.getChildAt(i), tx, ty, rotation);
                animator.setDuration(1000);
                animator.setStartDelay(50 * i);
                animators.add(animator);
            }

            animatorSet.playTogether(animators);
            animatorSet.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);

                    for (int i = 0; i < pokerStart.getChildCount(); i++) {
                        pokerStart.getChildAt(i).setTranslationX(0);
                        pokerStart.getChildAt(i).setTranslationY(0);
                        pokerStart.getChildAt(i).setVisibility(View.INVISIBLE);
                        parent.showBack();
                    }
                }

                @Override
                public void onAnimationStart(Animator animation) {
                    super.onAnimationStart(animation);
                    for (int i = 0; i < pokerStart.getChildCount(); i++) {
                        pokerStart.getChildAt(i).setVisibility(View.VISIBLE);
                    }
                }
            });
            return animatorSet;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onUserChange(User user) {
        this.user = user;
        initData();
    }

    private void checkChipsSelect(LinearLayout linearLayout, int select) {

        switch (select) {
            case 10000:
                if (chipsSelected == 10000 && (myDealTotal + select) * 6 > myAvailableTotal) {
                    chipsSelected = 1000;
                    changeChips(1000);
                }
                break;
            case 1000:
                if (chipsSelected == 1000 && (myDealTotal + select) * 6 > myAvailableTotal) {
                    chipsSelected = 100;
                    changeChips(100);
                }
                break;
            case 100:
                if (chipsSelected == 100 && (myDealTotal + select) * 6 > myAvailableTotal) {
                    chipsSelected = 10;
                    changeChips(10);
                }
                break;
        }
        if ((myDealTotal + select) * 6 > myAvailableTotal || user.getUserInfo().getRainbowSweet() < select * 6) {
            ((ImageView) linearLayout.getChildAt(0)).setImageBitmap(goldGray);
            ((TextView) linearLayout.getChildAt(1)).setTextColor(colorUnEnable);
            linearLayout.setEnabled(false);
        } else {
            ((ImageView) linearLayout.getChildAt(0)).setImageBitmap(gold);
            ((TextView) linearLayout.getChildAt(1)).setTextColor(colorWhite);
            linearLayout.setEnabled(true);
        }
    }

    private void initData() {
        tvCount.setText(user.getUserInfo().getRainbowSweet() + "");
        checkChipsSelect(llchips10000, 10000);
        checkChipsSelect(llchips1000, 1000);
        checkChipsSelect(llchips100, 100);
    }

    /**
     * 游戏逻辑处理
     */
    private static class GameHandler extends Handler {
        WeakReference<FragmentGameSanguo> weakReference;
        FragmentGameSanguo fragment;

        public GameHandler(FragmentGameSanguo context) {
            this.weakReference = new WeakReference<FragmentGameSanguo>(context);
            this.fragment = weakReference.get();
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_FAPAI: //发牌
                    fragment.doFapai();
                    break;
                case CODE_KAIPAI:  //开牌
                    fragment.kaipai((RainbowMessage.GCResultRet) msg.obj);
                    break;
                case CODE_DEAL:
                    removeMessages(CODE_CALCULATE_COUNTDOWN);
                    fragment.doActionDeal();
                    break;
                case CODE_DEAL_COUNTDOWN:
                    if (fragment.dealCountDown > 0) {
                        fragment.canDeal = true;
                        fragment.tvTimer.setVisibility(View.VISIBLE);
                        fragment.showCountDown(fragment.dealCountDown);
                        fragment.dealCountDown--;
                        L.e("TAG", "CODE_DEAL_COUNTDOWN 22222");
                        sendEmptyMessageDelayed(CODE_DEAL_COUNTDOWN, 1000);
                    } else {
                        fragment.tvTimer.setText("0");
                        fragment.dealCountDown = fragment.VAULE_DEALCOUNTDOWN;
                    }
                    break;
                case CODE_RELAX:
                    fragment.takeABreak();
                    break;
                case CODE_CALCULATE: //结算

                    fragment.doCalculateResult(msg.arg1);
                    break;
                case CODE_CALCULATE_COUNTDOWN://结算显示倒计时
                    int countdown = msg.arg1;
                    fragment.tvTimer.setVisibility(View.GONE);
                    removeMessages(CODE_DEAL_COUNTDOWN);
                    if (countdown > 0) {
                        fragment.tvTimer.setText("" + countdown);
                        countdown--;
                        msg = obtainMessage();
                        msg.arg1 = countdown;
                        msg.what = CODE_CALCULATE_COUNTDOWN;
                        sendMessageDelayed(msg, 1000);
                    } else {
                        fragment.tvTimer.setText("0");
                    }
                    break;
                case CODE_UPDATE_DEAL:
                    fragment.updateDealInfo((RainbowMessage.GCCathNowInfoRet) msg.obj);
                    break;
                case CODE_DEAL_RESULT:
                    try {
                        fragment.setDealView((RainbowMessage.GCBetRet) msg.obj);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case CODE_CHANGE_GAME:
                    fragment.changeGame((Integer) msg.obj);
                    break;
                case CODE_BANKER_LIST:
                    fragment.showBankerList((RainbowMessage.GCUpBankerListRet) msg.obj);
                    break;
                case CODE_UPDOWN_BANKER:
                    fragment.updownBankerResult();
                    break;
                case CODE_SWEET_COUNT:
                    fragment.updateSweet((RainbowMessage.GCNowSweetInfoRet) msg.obj);
                    break;
            }
        }
    }

    /*上下庄请求结果*/
    private void updownBankerResult() {
        if (mBankerID == Integer.parseInt(user.getUserId())) {// 下庄操作
//            showSnackbar(getRootView(mActivity), "下庄成功，本局结束自动下庄");
        } else {
            if (inBankerList) {
                showSnackbar(getRootView(mActivity), "取消成功，已退出上庄队列");
                inBankerList = false;
            } else {
                //showSnackbar(getRootView(mActivity), "上庄成功，已进入上庄排队中");
                inBankerList = true;
                getBankerList();
            }
        }
    }

    /*开牌动画*/
    private void kaipai(RainbowMessage.GCResultRet resultRet) {
        canDeal = false;
        if (GAMESTATE == 5) return;
        GAMESTATE = 5;
        int animTime = 2000;
        if (System.currentTimeMillis() - requestGameStateTime < 500) {
            animTime = 0;
        }
        if (tvTimer == null) return;
        tvTimer.setVisibility(View.GONE);
        tvState.setVisibility(View.GONE);
//        if (resultRet == null) return;
        sgLeft.showBack();
        sgCenter.showBack();
        sgRight.showBack();
        pgBanker.showBack();
        if (mBankerID != resultRet.getBankerId()) {
            mBankerID = resultRet.getBankerId();
            if (mBankerID != 0) {
                ((GameSanguoContract.Presenter) presenter).getBankerInfo("" + mBankerID);
            } else {
                showBankerInfo(null);
            }
        }
        List<Poker> bankerPokers = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            RainbowMessage.Card card = resultRet.getBankerCardsSet().getCards(i);
            Poker poker = new Poker(card.getCardNoShow(),
                    PokerView.PokerType.valueOf(card.getCardColor()));
            bankerPokers.add(poker);
        }

        if (pgBanker == null) {
            return;
        }
        pgBanker.setPokers(bankerPokers);
        pgBanker.setResult(resultRet.getBankerCardsSet().getNameNo());

        tvState.postDelayed(() -> {
            List<Poker> leftpokers = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                RainbowMessage.Card card = resultRet.getCardsSet1().getCards(i);
                Poker poker = new Poker(card.getCardNoShow(),
                        PokerView.PokerType.valueOf(card.getCardColor()));
                leftpokers.add(poker);
            }
            if (sgLeft == null) {
                return;
            }
            sgLeft.setPokers(leftpokers);
            sgLeft.setResult(resultRet.getCardsSet1().getNameNo());
            L.e(TAG, "rate  left :  " + resultRet.getCardsSet1().getRate()
                    + " poker type : " + resultRet.getCardsSet1().getNameNo());
            myWinLeft = calculateResult(
                    myDealLeft,
                    resultRet.getCardsSet1().getRate(),
                    resultRet.getCardsSet1().getIsWin()
            );
            if (Integer.parseInt(user.getUserId()) == mBankerID) {
                sgLeft.showResult(calculateResult(dealTotalLeft,
                        resultRet.getCardsSet1().getRate(),
                        (resultRet.getCardsSet1().getIsWin() + 1) % 2));
            } else {
                sgLeft.showResult(myWinLeft);
            }

        }, animTime);

        tvState.postDelayed(() -> {
            List<Poker> centerpokers = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                RainbowMessage.Card card = resultRet.getCardsSet2().getCards(i);
                Poker poker = new Poker(card.getCardNoShow(),
                        PokerView.PokerType.valueOf(card.getCardColor()));
                centerpokers.add(poker);
            }
            if (sgCenter == null) {
                return;
            }
            sgCenter.setPokers(centerpokers);
            sgCenter.setResult(resultRet.getCardsSet2().getNameNo());
            L.e(TAG, "rate  center  " + resultRet.getCardsSet2().getRate()
                    + " poker type : " + resultRet.getCardsSet2().getNameNo());
            myWinCenter = calculateResult(
                    myDealCenter,
                    resultRet.getCardsSet2().getRate(),
                    resultRet.getCardsSet2().getIsWin()
            );
            if (Integer.parseInt(user.getUserId()) == mBankerID) {
                sgCenter.showResult(calculateResult(dealTotalCenter,
                        resultRet.getCardsSet2().getRate(),
                        (resultRet.getCardsSet2().getIsWin() + 1) % 2));
            } else {
                sgCenter.showResult(myWinCenter);
            }
        }, animTime * 2);

        tvState.postDelayed(() -> {
            List<Poker> rightpokers = new ArrayList<>();
            for (int i = 0; i < 5; i++) {
                RainbowMessage.Card card = resultRet.getCardsSet3().getCards(i);
                Poker poker = new Poker(card.getCardNoShow(),
                        PokerView.PokerType.valueOf(card.getCardColor()));
                rightpokers.add(poker);
            }
            if (sgRight == null) {
                return;
            }
            sgRight.setPokers(rightpokers);
            sgRight.setResult(resultRet.getCardsSet3().getNameNo());
            L.e(TAG, "rate  right  " + resultRet.getCardsSet3().getRate()
                    + " poker type : " + resultRet.getCardsSet3().getNameNo());
            myWinRight = calculateResult(
                    myDealRight,
                    resultRet.getCardsSet3().getRate(),
                    resultRet.getCardsSet3().getIsWin()
            );
            if (Integer.parseInt(user.getUserId()) == mBankerID) {
                sgRight.showResult(calculateResult(dealTotalRight,
                        resultRet.getCardsSet3().getRate(),
                        (resultRet.getCardsSet3().getIsWin() + 1) % 2));
            } else {
                sgRight.showResult(myWinRight);
            }
        }, animTime * 3);

        tvState.postDelayed(() -> {
            calculateResult(resultRet.getBankerflow());
        }, (long) (animTime * 3.5));
    }

    /*计算结果*/
    private int calculateResult(int deal, int rate, int isWin) {

        if (isWin == 0) {  //输
            return -deal * rate;
        } else {
            return deal * rate;
        }
    }

    private int calculateResult(int bankerFlow) {
        canDeal = false;
        int result = 0;
        result = myWinLeft + myWinCenter + myWinRight;
        int rainBowSweet = user.getUserInfo().getRainbowSweet();
        if (result > 0) {
            result -= Math.floor(result * serviceRate);
        }
        rainBowSweet += (result + myDealLeft + myDealRight + myDealCenter);

        if (myDealTotal > 0) {
            user.getUserInfo().setFreezeSweet(0);
            user.getUserInfo().setRainbowSweet(rainBowSweet);
            myDealTotal = 0;
            UserProxy.setUser(user);
        }
        showSettleView(bankerFlow);
        getRainbowSweet(mBankerID);
        getRainbowSweet(Integer.parseInt(user.getUserId()));
        return Math.max(0, result);
    }

    /*显示当局结算*/
    private void showSettleView(int bankerFlow) {
        if (llSettle == null) return;
        if (llSettle.getVisibility() != View.VISIBLE) {
            llSettle.setVisibility(View.VISIBLE);
            llSettle.startAnimation(stateShowAnim);
        }
        if (bankerFlow >= 0) {
            tvSettleBanker.setText(String.format(settleBanker, "+" + bankerFlow));
        } else {
            tvSettleBanker.setText(String.format(settleBanker, "" + bankerFlow));
        }
        int mine = myWinLeft + myWinCenter + myWinRight;
        if (mine >= 0) {
            tvSettleMine.setText(String.format(settleMine,
                    "+" + (int) (mine - Math.floor(mine * (serviceRate)))));
        } else {
            tvSettleMine.setText(String.format(settleMine, "" + mine));
        }
    }

    /*初始化历史记录对话框*/
    private void initHisResultDialog() {
        if (hisResult == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.layout_history_result, null);
            hisResult = new CustomDialog(mActivity, view);
            lvHistory = (ListView) view.findViewById(R.id.lvHistory);
            view.findViewById(R.id.ivCancel).setOnClickListener(
                    (v) -> hisResult.hide()
            );
            ImageView ivWinLeft = (ImageView) view.findViewById(R.id.ivWinLeft);
            ivWinLeft.setImageResource(R.drawable.icon_liub_samll);
            ImageView ivWinCenter = (ImageView) view.findViewById(R.id.ivWinCenter);
            ivWinCenter.setImageResource(R.drawable.icon_gy_samll);
            ImageView inWinRight = (ImageView) view.findViewById(R.id.ivWinRight);
            inWinRight.setImageResource(R.drawable.icon_zf_samll);
            TextView tvLeft = (TextView) view.findViewById(R.id.tvLeft);
            TextView tvCenter = (TextView) view.findViewById(R.id.tvCenter);
            TextView tvRight = (TextView) view.findViewById(R.id.tvRight);
            tvLeft.setText("刘备");
            tvCenter.setText("关羽");
            tvRight.setText("张飞");
            hisAdapter = new NiuNiuHistoryAdapter(mActivity, mHisDatas);
            lvHistory.setAdapter(hisAdapter);
            hisResult.hide();
        }
    }

    /*初始化庄家流水对话框*/
    private void initBankerFlowDialog() {
        if (bankerFlowDialog == null) {
            View view = LayoutInflater.from(mActivity).inflate(R.layout.dialog_sanguo_stream, null);
            bankerFlowDialog = new CustomDialog(mActivity, view);
            view.findViewById(R.id.ivCancel).setOnClickListener(
                    (v) -> bankerFlowDialog.hide()
            );
            bankerFlowAdapter = new BankerFlowAdapter(bankerFlowDatas, mActivity);
            ListView lvFlow = (ListView) bankerFlowDialog.findViewById(R.id.lvFlow);
            lvFlow.setAdapter(bankerFlowAdapter);
            bankerFlowDialog.hide();
        }
    }

    private void showBankerFlowDialog(BankerFlowData data) {
        if (!data.getFlow().isEmpty()) {
            bankerFlowDatas.clear();
            bankerFlowDatas.addAll(data.getFlow());
        }
        bankerFlowAdapter.notifyDataSetChanged();
        TextView bankerFlow = (TextView) bankerFlowDialog.findViewById(R.id.tvBankerFlow);
        int flow = data.getTotalFlow();
        bankerFlow.setText(flow >= 0 ? Html.fromHtml(String.format(bankerFlowPositive, flow)) :
                Html.fromHtml(String.format(bankerFlowNegative, flow)));
        bankerFlowDialog.show();
    }

    /*下庄提醒dialog*/
    private void initDownBankerDialog() {
        if (downBankerDialog == null) {
            View view = View.inflate(mActivity, R.layout.layout_choose_dialog, null);
            downBankerDialog = new CustomDialog(mActivity, view);
            downBankerDialog.hide();
            TextView tvContent = (TextView) view.findViewById(R.id.tvContent);
            tvContent.setText("当前游戏结束后，自动下庄，是否确认下庄?");
            view.findViewById(R.id.btnCancel).setOnClickListener((v -> {
                downBankerDialog.hide();
            }));
            TextView tvSure = (TextView) view.findViewById(R.id.btnSure);
            tvSure.setText("确定");
            tvSure.setOnClickListener((v -> {
                sendUpDownBankerMsg2Server(0);
                downBankerDialog.hide();
            }));
        }
    }

    /*下注倒计时*/
    private TextView showCountDown(int countdown) {
        tvTimer.setText(String.valueOf(countdown));
        tvTimer.setVisibility(View.VISIBLE);
        return tvTimer;
    }

    /*休息一会*/
    private void takeABreak() {
        if (switchGameID < 0) {
            // ((FragmentLayer) getParentFragment()).switchGame(switchGameID);
            cleanData();
            if (tvState == null) return;
            sgLeft.hide();
            sgRight.hide();
            pgBanker.hide();
            sgCenter.hide();
            showState("即将开始，请稍后");
        } else if (switchGameID == 0) {
            L.e(TAG,"BBBBBBBBBBBB   22222");
            ((FragmentLayer) getParentFragment()).deleteGame();
        }
        llSettle.setVisibility(View.GONE);
    }

    /*游戏开始清空上一局数据*/
    private void cleanData() {
        if (sgLeft == null) return;
        pgBanker.clean();
        sgLeft.clean();
        sgCenter.clean();
        sgRight.clean();
        myDealCenter = 0;
        myDealRight = 0;
        myDealLeft = 0;
        myDealTotal = 0;

        dealTotalLeft = 0;
        dealTotalCenter = 0;
        dealTotalRight = 0;

        myAvailableTotal = user.getUserInfo().getRainbowSweet();
        Observerable.getInstance().notifyChange(ObserverableType.HASDEAL, false);
    }

    /*结算阶段 */
    private void doCalculateResult(int countdown) {
        canDeal = false;
        if (sgLeft == null) return;
        sgLeft.showBack();
        pgBanker.showBack();
        sgCenter.showBack();
        sgRight.showBack();
        dealCountDown = 0;
        tvTimer.setVisibility(View.GONE);
        tvTimer.setText("" + countdown);
        Message msg = mHandler.obtainMessage();
        msg.arg1 = countdown;
        msg.what = CODE_CALCULATE_COUNTDOWN;
        mHandler.sendMessage(msg);
        showState("揭晓结果");
    }

    /*下注阶段*/
    private void doActionDeal() {
        canDeal = true;
        if (sgLeft == null) return;
        sgLeft.showBack();
        sgCenter.showBack();
        pgBanker.showBack();
        sgRight.showBack();
        if (tvState != null) {
            tvState.setVisibility(View.GONE);
            mHandler.sendEmptyMessage(CODE_DEAL_COUNTDOWN);
            L.e(TAG, "CODE_DEAL_COUNTDOWN    11111");
            tvTimer.setVisibility(View.VISIBLE);
        }
    }


    /*长连回调--------------------------------------------*/
    @Override
    public void onConnected(IoSession session) {
        getGameState();
        if (mActivity instanceof LiveRoomActivity) {
            getDealInfo();
        }
        getRainbowSweet(Integer.parseInt(user.getUserId()));
    }

    @Override
    public void onException(IoSession session, Throwable cause) {

    }

    @Override
    public void onReceiveMessage(IoSession session, Object message) {
        Packet packet = (Packet) message;
        L.e(TAG, "GAMEState " + packet.getRetCode());
        Message msg;
        try {
            switch (packet.getPacketId()) {
                case HOpCodeEx.GCOpenRet:
                    RainbowMessage.GCOpenRet openResult = RainbowMessage.GCOpenRet.parseFrom((byte[]) packet.getData());
                    if (openResult.getCode() == 0) {//开局成功
                        chessboardId = openResult.getChessboardId();
                        msg = mHandler.obtainMessage();
                        msg.what = CODE_FAPAI;
                        msg.obj = openResult;
                        mHandler.sendMessage(msg);
                    } else {
                        showToast("服务器开局失败");
                        chessboardId = 0;
                    }

                    break;
                case HOpCodeEx.GCResultRet:
                    RainbowMessage.GCResultRet result = RainbowMessage.GCResultRet.parseFrom((byte[]) packet.getData());
                    L.e(TAG, "GAMESTATE  游戏状态 5 开牌 GAMEID = " + result.getGameId());
                    if (result.getCode() == 0) {//返回成功
                        if (result.getGameId() != GAME_ID && result.getGameId() != 0) {
                            if (shouldNotChange){
//                                ((FragmentLayer)getParentFragment()).deleteGame();
                                MinaHelper.getInstance().removeCallback(this);
                            }else {
                                msg = mHandler.obtainMessage();
                                msg.obj = result.getGameId();
                                msg.what = CODE_CHANGE_GAME;
                                mHandler.sendMessage(msg);
                            }
                        } else {
                            niuniuResult = result;
                            msg = mHandler.obtainMessage();
                            msg.obj = niuniuResult;
                            msg.what = CODE_KAIPAI;
                            mHandler.sendMessage(msg);
                        }
                    } else {
                        showToast("服务器返回错误：code " + result.getCode());
                        chessboardId = 0;
                    }
                    break;
                case HOpCodeEx.GCGameStateRet:
                    doGameAction(packet);
                    break;
                case HOpCodeEx.GCCathNowInfoRet:
                    L.e(TAG, "下注 筹码池");
                    RainbowMessage.GCCathNowInfoRet dealInfo = RainbowMessage.GCCathNowInfoRet.parseFrom((byte[]) packet.getData());
                    msg = mHandler.obtainMessage();
                    msg.obj = dealInfo;
                    msg.what = CODE_UPDATE_DEAL;
                    mHandler.sendMessage(msg);
                    break;
                case HOpCodeEx.GCBetRet:
                    L.e(TAG, "time  return " + System.currentTimeMillis());
                    //下注成功
                    L.e(TAG, "下注成功返回");
                    RainbowMessage.GCBetRet gcBetRet = RainbowMessage.GCBetRet.parseFrom((byte[]) packet.getData());
                    msg = mHandler.obtainMessage();
                    msg.what = CODE_DEAL_RESULT;
                    msg.obj = gcBetRet;
                    mHandler.sendMessage(msg);

                    break;
                case HOpCodeEx.GCNowSweetInfoRet:
                    L.e(TAG, "rainbowsweet ");
                    RainbowMessage.GCNowSweetInfoRet gcNowSweetInfoRet = RainbowMessage.GCNowSweetInfoRet.parseFrom((byte[]) packet.getData());
                    msg = mHandler.obtainMessage();
                    msg.what = CODE_SWEET_COUNT;
                    msg.obj = gcNowSweetInfoRet;
                    mHandler.sendMessage(msg);
                    break;
                case HOpCodeEx.GCUpBankerListRet:
                    L.e(TAG, "庄家列表");
                    if (packet.getData() != null) {
                        RainbowMessage.GCUpBankerListRet gcBankerList = RainbowMessage.GCUpBankerListRet.parseFrom((byte[]) packet.getData());
                        msg = mHandler.obtainMessage();
                        msg.what = CODE_BANKER_LIST;
                        msg.obj = gcBankerList;
                        mHandler.sendMessage(msg);
                    } else {
                        msg = mHandler.obtainMessage();
                        msg.what = CODE_BANKER_LIST;
                        msg.obj = null;
                        mHandler.sendMessage(msg);
                    }

                    break;
                case HOpCodeEx.GCUpDownBankerRet:
                    RainbowMessage.GCUpDownBankerRet gcUpDownBankerRet =
                            RainbowMessage.GCUpDownBankerRet.parseFrom((byte[]) packet.getData());
                    if (gcUpDownBankerRet.getCode() == 0) {
                        mHandler.sendEmptyMessage(CODE_UPDOWN_BANKER);
                    }
                    break;
                case HOpCodeEx.GCUserStateRet:
                    RainbowMessage.GCUserStateRet gcUserStateRet = RainbowMessage.GCUserStateRet.parseFrom((byte[]) packet.getData());
                    L.e(TAG, "gcUserStateRet " + "liveid :" + gcUserStateRet.getLiveId()
                            + "   isbanker :" + gcUserStateRet.getIsBanker()
                            + "   notsettle :" + gcUserStateRet.getNotSettleSweet()
                            + "   frzee :" + gcUserStateRet.getFreezeSweet());
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDisConnected(IoSession session) {

    }

    /*长连回调---------------------------end-----------------*/

    private void updateSweet(RainbowMessage.GCNowSweetInfoRet data) {
        if (data.getUserId() != Integer.parseInt(user.getUserId())) {  //庄家
            updateBankerSweet(data.getTotalSweet());
        } else {
            UserInfo info = user.getUserInfo();
            info.setFreezeSweet(data.getFreezeSweet());
            info.setAvailableSweet(data.getFreezeSweet());
            info.setRainbowSweet(data.getTotalSweet());
            user.setUserInfo(info);
            UserProxy.setUser(user);

            if (Integer.parseInt(user.getUserId()) == mBankerID) {
                updateBankerSweet(info.getRainbowSweet());
            }
        }

    }

    private void updateBankerSweet(int sweet) {
        if (mBankerID > 1)
            tvBankerGold.setText(FormatUtil.formatDealTotal(sweet));
    }

    /*游戏行为*/
    private void doGameAction(Packet packet) throws InvalidProtocolBufferException {
        RainbowMessage.GCGameStateRet gameStateRet = RainbowMessage.GCGameStateRet.parseFrom((byte[]) packet.getData());
        L.e(TAG, "GAMEState 游戏状态 " + gameStateRet.getState()
                + "  游戏局ID " + chessboardId
                + " 游戏id " + gameStateRet.getGameId()
                + "  倒计时 " + gameStateRet.getCountDown()
                + " 庄家ID " + gameStateRet.getBankerId()
        );
        if (gameStateRet.getBankerId() != mBankerID) {
            mBankerID = gameStateRet.getBankerId();
            if (mBankerID != 0) {
                ((GameSanguoContract.Presenter) presenter).getBankerInfo("" + mBankerID);
            } else {
                showBankerInfo(null);
            }
        }
        if (gameStateRet.getGameId() != GAME_ID && gameStateRet.getGameId() != 0) {   //游戏id 和 当前游戏不一致，切游戏
            Message msg = mHandler.obtainMessage();
            msg.obj = gameStateRet.getGameId();
            msg.what = CODE_CHANGE_GAME;
            mHandler.sendMessage(msg);
        } else {
            if (GAMESTATE == gameStateRet.getState()) {
                return;
            }
            chessboardId = gameStateRet.getChessboardId();
            GAMESTATE = gameStateRet.getState();
            Message msg;
            switch (gameStateRet.getState()) {
                case 1:
                    L.e(TAG, "GAMEState 即将开始   " + new Date(System.currentTimeMillis()).toLocaleString());
                    if (switchGameID > 0) {  //切换游戏
                        ((FragmentLayer) getParentFragment()).switchGame(switchGameID);
                        L.e(TAG,"CCCCCCCCCCCCCCCCCCCCC     6666666666");
                    } else if (switchGameID == 0) {
                        ((FragmentLayer) getParentFragment()).deleteGame();
                    } else {
                        mHandler.sendEmptyMessage(CODE_RELAX);
                    }
                    break;
                case 2: //发牌
                    L.e(TAG, "GAMEState 发牌   " + new Date(System.currentTimeMillis()).toLocaleString());
                    msg = mHandler.obtainMessage();

                    msg.what = CODE_FAPAI;
                    mHandler.sendMessage(msg);
                    break;
                case 3: //开始下注
                    L.e(TAG, "GAMEState 开始下注   " + new Date(System.currentTimeMillis()).toLocaleString());
                    dealCountDown = gameStateRet.getCountDown();
                    if (dealCountDown < 0) {
                        dealCountDown = 20;
                    }
                    mHandler.sendEmptyMessage(CODE_DEAL);
                    canDeal = true;
                    break;
                case 4:
                    L.e(TAG, "GAMEState 结算   " + new Date(System.currentTimeMillis()).toLocaleString());
                    int countDown = gameStateRet.getCountDown();
                    if (countDown <= 0) countDown = 5;
                    msg = mHandler.obtainMessage();
                    msg.what = CODE_CALCULATE;
                    msg.arg1 = countDown;
                    mHandler.sendMessage(msg);
                    break;
                case 5:
                    L.e(TAG, "GAMEState 开牌   " + new Date(System.currentTimeMillis()).toLocaleString());
                    mHandler.sendEmptyMessage(CODE_RELAX);
                    break;
                default:
                    break;
            }
        }
    }

    /*获取下注信息*/
    private void getDealInfo() {
        RainbowMessage.CGCathNowInfo.Builder builder = RainbowMessage.CGCathNowInfo.newBuilder();
        builder.setUserId(Integer.parseInt(user.getUserId()));
        builder.setLiveId(liveID);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGCathNowInfo, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }

    /*获取游戏状态*/
    public void getGameState() {
        L.e(TAG, "请求游戏状态");
        requestGameStateTime = System.currentTimeMillis();
        RainbowMessage.CGGameState.Builder open = RainbowMessage.CGGameState.newBuilder();
        open.setLiveId(liveID);
        open.setGameId(GAME_ID);
        open.setUserId(Integer.parseInt(UserProxy.getUser().getUserId()));
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGGameState, open.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
        L.e(TAG, "请求游戏状态 liveID " + liveID + "UserID  " + UserProxy.getUser().getUserId());
    }

    /*更新下注情况*/
    private void updateDealInfo(RainbowMessage.GCCathNowInfoRet dealInfo) {
        if (sgLeft == null) return;
        sgLeft.setDealTotal(dealInfo.getIndex1Total());
        dealTotalLeft = dealInfo.getIndex1Total();

        sgCenter.setDealTotal(dealInfo.getIndex2Total());
        dealTotalCenter = dealInfo.getIndex2Total();
        //center.doDeal(dealInfo.getIndex2User());
        sgRight.setDealTotal(dealInfo.getIndex3Total());
        dealTotalRight = dealInfo.getIndex3Total();
        //right.doDeal(dealInfo.getIndex3User());

        updateDealInfoAsFirst(dealInfo);
    }

    private void updateDealInfoAsFirst(RainbowMessage.GCCathNowInfoRet dealInfo) {
        if (mActivity instanceof LiveRoomActivity) {
            if (dealInfo.getIndex1User() > 0) {
                sgLeft.doDeal(dealInfo.getIndex1User());
                myDealLeft = dealInfo.getIndex1User();
            }
            if (dealInfo.getIndex2User() > 0) {
                sgCenter.doDeal(dealInfo.getIndex2User());
                myDealCenter = dealInfo.getIndex2User();
            }

            if (dealInfo.getIndex3User() > 0) {
                sgRight.doDeal(dealInfo.getIndex3User());
                myDealRight = dealInfo.getIndex3User();
            }
            if (myDealLeft + myDealCenter + myDealRight > 0) {
                myDealTotal = myDealLeft + myDealCenter + myDealRight;
                if (myAvailableTotal == 0 || myAvailableTotal == user.getUserInfo().getRainbowSweet()) {
                    myAvailableTotal = user.getUserInfo().getRainbowSweet() - myDealTotal;
                    initData();
                }
            }
        }
    }

    /*切换游戏*/
    private void changeGame(int gameID) {
        FragmentLayer layer = (FragmentLayer) getParentFragment();
        layer.switchGame(gameID);
        L.e(TAG,"CCCCCCCCCCCCCCCCCCCCC     7777777777777");
    }

    private void setDealView(RainbowMessage.GCBetRet betRet) throws Exception {
        if (sgLeft == null) return;
        if (betRet.getCode() == 0) {
            int index = betRet.getIndex();
            switch (index) {
                case 1:
                    doDeal(chipsSelected, myDealLeft, 1);
                    break;
                case 2:
                    doDeal(chipsSelected, myDealCenter, 2);
                    break;
                case 3:
                    doDeal(chipsSelected, myDealRight, 3);
                    break;
            }
        } else if (betRet.getCode() == 1) {
            showSnackbar(getRootView(mActivity), "余额不足");
        } else if (betRet.getCode() == 2) {
            showSnackbar(getRootView(mActivity), "余额不足(已下注)");
        } else if (betRet.getCode() == 3) {
            showSnackbar(getRootView(mActivity), "已达下注上限");
        }

    }

    private boolean doDeal(int num, int total, int index) {
        UserInfo info = user.getUserInfo();
        if (info.getRainbowSweet() >= num) {
            total += num;
            switch (index) {
                case 1:
                    myDealLeft = total;
                    sgLeft.doDeal(myDealLeft);
                    break;
                case 2:
                    myDealCenter = total;
                    sgCenter.doDeal(myDealCenter);
                    break;
                case 3:
                    myDealRight = total;
                    sgRight.doDeal(myDealRight);
                    break;
            }
            myDealTotal += num;
            info.setRainbowSweet(info.getRainbowSweet() - num);
            info.setFreezeSweet(myDealTotal * 5);
            user.setUserInfo(info);
            UserProxy.setUser(user);
            Observerable.getInstance().notifyChange(ObserverableType.HASDEAL, true);
            return true;
        } else {
            showToast("彩虹糖不足，请充值");
            return false;
        }
    }

    @Override
    public void setPresenter(GameSanguoContract.Presenter presenter) {
        this.presenter = presenter;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showHistoryResult(BaseData<List<NiuniuHistory>> results) {
        mHisDatas.clear();
        mHisDatas.addAll(results.getObject());
        hisAdapter.notifyDataSetChanged();
        lvHistory.measure(0, 0);
        ViewGroup.LayoutParams layoutParams = lvHistory.getLayoutParams();
        if (mHisDatas.size() >= 6) {
            layoutParams.height = DeviceUtils.dp2px(mActivity, 245);
            lvHistory.setLayoutParams(layoutParams);
        }
        hisResult.show();
    }

    @Override
    public void setGameInfo(GameInfo gameInfo) {
        this.gameInfo = gameInfo;
        if (myAvailableTotal == 0) {
            myAvailableTotal = user.getUserInfo().getRainbowSweet();
            initGame();
        }
    }

    @Override
    public void showBankerInfo(BaseData<UserInfo> data) {
        if (mBankerID == 1) { // 吕布
            tvBankerName.setText("吕布");
            ivBankerHeader.setImageResource(R.drawable.icon_lb);
            tvBankerGold.setText(FormatUtil.formatDealTotal(100000));
            tvBeBanker.setText("我要上庄");
            if (GAMESTATE == 1) {
                ((FragmentLayer) getParentFragment()).sendNotifyMessage("玩家吕布上庄", false);
            }
            Observerable.getInstance().notifyChange(ObserverableType.ISBANKER, false);
        } else {
            if (data != null && data.getObject() != null) {
                GlideUtil.load(mActivity, data.getObject().getIcon(), ivBankerHeader);
                tvBankerName.setText(data.getObject().getNickname());
                tvBankerGold.setText(FormatUtil.formatDealTotal(data.getObject().getRainbowSweet()));
                if (mBankerID == Integer.parseInt(user.getUserId())) {
                    tvBeBanker.setText("我要下庄");
                    if (GAMESTATE == 1) {
                        ((FragmentLayer) getParentFragment()).sendNotifyMessage("玩家" + data.getObject().getNickname() + "上庄");
                    }
                    Observerable.getInstance().notifyChange(ObserverableType.ISBANKER, true);
                } else {
                    tvBeBanker.setText("我要上庄");
                }
            }
        }
    }

    @Override
    public void showBankerFlow(BaseData<BankerFlowData> data) {
        if (data.getCode() == 0) {
            showBankerFlowDialog(data.getObject());
        }
    }

    private void initGame() {
        rateLeft = gameInfo.getRateFirst();
        rateCenter = gameInfo.getRateSecond();
        rateRight = gameInfo.getRateThird();

        initData();
    }

    @Override
    public void onDestroy() {
        hisResult.dismiss();
        bankerFlowDialog.dismiss();
        bankerListDialog.dismiss();
        downBankerDialog.dismiss();
        MinaHelper.getInstance().removeCallback(this);
        mHandler.removeCallbacksAndMessages(null);
        UserProxy.removeListener(this);
        super.onDestroy();
        L.e(TAG, "ondestory    niuniu  " + AppConfig.isJumpFromLive);
    }

    /**
     * 上下庄
     *
     * @param type 1 上庄  0 下装
     */
    private void sendUpDownBankerMsg2Server(int type) {
        RainbowMessage.CGUpDownBanker.Builder builder = RainbowMessage.CGUpDownBanker.newBuilder();
        builder.setLiveId(liveID);
        builder.setUserId(Integer.parseInt(user.getUserId()));
        builder.setToken(user.getToken());
        builder.setUpOrDown(type);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGUpDownBanker, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }

    /*请求上庄列表*/
    private void getBankerList() {
        RainbowMessage.CGUpBankerList.Builder builder = RainbowMessage.CGUpBankerList.newBuilder();
        builder.setLiveId(liveID);
        builder.setGameId(GAME_ID);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGUpBankerList, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }

    /*上庄排队列表*/
    private void showBankerList(RainbowMessage.GCUpBankerListRet data) {
        if (bankerListDialog.isShowing()) {
            bankerList.clear();
            if (data != null) {
                List<RainbowMessage.User> upUsers = data.getUserList();
                bankerList.addAll(upUsers);
            }
            inBankerList = false;
            for (RainbowMessage.User item : bankerList) {
                if (item.getUserId() == Integer.parseInt(user.getUserId())) {
                    inBankerList = true;
                    break;
                }
            }
            TextView tvBeBanker = (TextView) bankerListDialog.findViewById(R.id.tvBeBanker);
            if (inBankerList) {
                tvBeBanker.setText("我要下庄");
            } else {
                tvBeBanker.setText("我要上庄");
            }
            bankerListAdapter.notifyDataSetChanged();
        } else {
            bankerList.clear();
            if (data != null) {
                List<RainbowMessage.User> upUsers = data.getUserList();
                bankerList.addAll(upUsers);
            }
            inBankerList = false;
            for (RainbowMessage.User item : bankerList) {
                if (item.getUserId() == Integer.parseInt(user.getUserId())) {
                    inBankerList = true;
                    break;
                }
            }
            bankerListAdapter.notifyDataSetChanged();
            showBankerListDialog(inBankerList);
        }
    }

    /*初始化上庄列表dialog*/
    private void initBankerListDialog() {
        if (bankerListDialog == null) {
            View view = View.inflate(mActivity, R.layout.dialog_bankerlist, null);
            bankerListDialog = new CustomDialog(mActivity, view);
            bankerListDialog.hide();
            ListView lvBankers = (ListView) view.findViewById(R.id.lvBankers);
            bankerListAdapter = new BankerListAdapter(bankerList, mActivity);
            lvBankers.setAdapter(bankerListAdapter);
            view.findViewById(R.id.ivCancel).setOnClickListener(
                    (v) -> bankerListDialog.hide()
            );
        }
    }

    /*显示上庄列表dialog*/
    private void showBankerListDialog(boolean inList) {
        bankerListDialog.show();
        TextView tvBeBanker = (TextView) bankerListDialog.findViewById(R.id.tvBeBanker);
        if (inList) {
            tvBeBanker.setText("我要下庄");
        } else {
            tvBeBanker.setText("我要上庄");
        }
        tvBeBanker.setOnClickListener((view) -> {
            if (inBankerList) {
                sendUpDownBankerMsg2Server(0);
                bankerListDialog.hide();
            } else {
                sendUpDownBankerMsg2Server(1);
            }
        });

    }

    private void getRainbowSweet(int id) {
        RainbowMessage.CGNowSweetInfo.Builder builder = RainbowMessage.CGNowSweetInfo.newBuilder();
//        builder.setToken(user.getToken());
        builder.setUserId(id);
        Packet packet = Packet.newPbPacket(HOpCodeEx.CGNowSweetInfo, builder.build().toByteArray());
        packet.setFlag(9);
        packet.setStamp(System.currentTimeMillis());
        packet.setRetCode(0);
        MinaHelper.getInstance().sendMessageToServer(packet);
    }
}
